package com.github.davidfantasy.mybatisplus.generatorui;

import com.github.davidfantasy.mybatisplus.generatorui.configurer.GeneratorConfig;
import com.github.davidfantasy.mybatisplus.generatorui.configurer.MybatisPlusToolsApplication;
import com.github.davidfantasy.mybatisplus.generatorui.mbp.NameConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.FileSystemResource;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

@Slf4j
@SpringBootApplication
public class App implements CommandLineRunner {

    static String configFileName = "pui.yml";

    static int port = 8068;

    static Function<PropertySource,String> userName = p->String.valueOf(p.getProperty("username"));
    static Function<PropertySource,String> password = p->String.valueOf(p.getProperty("password"));
    static Function<PropertySource,String> driver = p->String.valueOf(p.getProperty("driver"));
    static Function<PropertySource,String> jdbcUrl = p->String.valueOf(p.getProperty("jdbcUrl"));
    static Function<PropertySource,String> basePackage = p->String.valueOf(p.getProperty("basePackage"));
    static Function<PropertySource,String> prefix = p->String.valueOf(Optional.ofNullable(p.getProperty("prefix")).orElse(""));

    public static class PrefixNameConverter implements NameConverter {

        private String prefix;

        public PrefixNameConverter(String prefix){
            this.prefix=prefix;
        }

        @Override
        public String entityNameConvert(String tableName) {
            log.info("add prefix {}",prefix);
            return prefix+NameConverter.super.entityNameConvert(tableName);
        }
    }

    public static void main(String[] args) throws IOException {

        YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();

        //获取当前目录
        String currentPath = System.getProperty("user.dir");
        FileSystemResource fileSystemResource = new FileSystemResource(currentPath + File.separator + configFileName);
        log.info("start load config file `pui.yml` on path {}",fileSystemResource.getPath());
        if(!fileSystemResource.exists()){
            log.error("not fount config file at project root dir,Consider adding a `pui.yml` file to your project, exit!");
            return;
        }
        List<PropertySource<?>> load = yamlPropertySourceLoader.load(fileSystemResource.getFilename(), fileSystemResource);
        PropertySource<?> propertySource = load.get(0);


        if(args.length!=0){
            port = Integer.parseInt(args[0]);
        }
        GeneratorConfig config = GeneratorConfig.builder()
                .jdbcUrl(jdbcUrl.apply(propertySource))
                .userName(userName.apply(propertySource))
                .password(password.apply(propertySource))
                .port(port)
                .driverClassName(driver.apply(propertySource))
                .basePackage(basePackage.apply(propertySource))
                .nameConverter(new PrefixNameConverter(prefix.apply(propertySource)))
                .build();
        MybatisPlusToolsApplication.run(config);
    }


    public void openBrowser(int port){
        String url = "http://localhost:"+port;
        try {
            Desktop desktop = Desktop.getDesktop();
            if (desktop.isSupported(Desktop.Action.BROWSE)) {
                desktop.browse(java.net.URI.create(url));
            }else {
                System.err.println("当前电脑不支持自动打开游览器，请在游览器中手动打开 "+url);
            }
        } catch (Exception e) {
            System.err.println("自动打开游览器失败，请在游览器中手动打开 "+url);
        }
    }

    @Override
    public void run(String... args) throws Exception {
        openBrowser(port);
    }

}
